package com.example.horizonserver.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.horizonserver.config.RabbitConfig;
import com.example.horizonserver.mapper.VehicleMapper;
import com.example.horizonserver.pojo.entity.Vehicle;
import com.example.horizonserver.pojo.message.DispatchVehicleMessage;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Map;

@Component
@RequiredArgsConstructor
public class VehicleListener {

    private final VehicleMapper vehicleMapper;

    @RabbitListener(queues = RabbitConfig.DISPATCH_QUEUE)
    @Transactional
    public void handleVehicleMessage(DispatchVehicleMessage message) {
        Integer vehicleId = message.getVehicleId();
        String action = message.getAction();
        Integer userRole = message.getUserRole();
        LocalDateTime lastUseTime = message.getLastUseTime();

        // 根据 action 决定车辆状态 并更改上次使用时间
        switch (action) {
            case "SUBMIT":
                updateStatusAndLastUseTime(vehicleId, userRole==1?2:4,lastUseTime);
                break;
            case "CONFIRM":
                updateStatusAndLastUseTime(vehicleId, 2,lastUseTime); // 在用
                break;
            case "REJECTION":
                updateStatusAndLastUseTime(vehicleId, 1,lastUseTime); // 可用
                break;
            case "COMPLETE":
                updateStatusAndLastUseTime(vehicleId, 1,lastUseTime); // 归还后可用
                break;
        }
    }

    private void updateStatusAndLastUseTime(Integer vehicleId, Integer status, LocalDateTime lastUseTime)
    {
        vehicleMapper.update(Wrappers.<Vehicle>lambdaUpdate()
                .eq(Vehicle::getId,vehicleId)
                .set(Vehicle::getStatus,status)
                .set(Vehicle::getLastUseTime,lastUseTime));
    }
}
